#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
修复Java文件中的中文注释乱码问题
"""
import os
import re
import chardet
from pathlib import Path

def is_garbled_chinese(text):
    """检查文本中是否有乱码的中文字符"""
    if not text:
        return False
    
    # 检查是否有常见的乱码模式
    garbled_patterns = [
        r'[\x80-\xff]{2,}',  # 连续的非ASCII字符，可能是乱码
        r'æ|è|ø|Ã|©|®|¼|½|¾',  # 常见的乱码字符
    ]
    
    for pattern in garbled_patterns:
        if re.search(pattern, text):
            return True
    
    return False

def generate_method_comment(method_name, return_type, param_names):
    """根据方法名和参数生成英文注释"""
    # 根据常见的命名模式生成注释
    comment = ""
    
    # 基本方法类型判断
    if method_name.startswith("get"):
        comment = f"Gets the {method_name[3:].lower()}"
    elif method_name.startswith("set"):
        comment = f"Sets the {method_name[3:].lower()}"
    elif method_name.startswith("is"):
        comment = f"Checks if {method_name[2:].lower()}"
    elif method_name.startswith("create"):
        comment = f"Creates a new {method_name[6:].lower()}"
    elif method_name.startswith("delete") or method_name.startswith("remove"):
        comment = f"Deletes or removes {method_name[6:].lower()}"
    elif method_name.startswith("update") or method_name.startswith("modify"):
        comment = f"Updates or modifies {method_name[6:].lower()}"
    elif "serialize" in method_name.lower():
        comment = "Serializes the object to the specified format"
    elif "deserialize" in method_name.lower():
        comment = "Deserializes the data from the specified format"
    elif method_name.lower().endswith("handler"):
        comment = f"Handles {method_name[:-7].lower()} operations"
    elif method_name.lower().endswith("processor"):
        comment = f"Processes {method_name[:-9].lower()} data"
    elif method_name.lower().endswith("manager"):
        comment = f"Manages {method_name[:-7].lower()} resources"
    elif method_name.lower().endswith("service"):
        comment = f"Provides {method_name[:-7].lower()} service"
    elif method_name == "main":
        comment = "Main entry point for the application"
    else:
        comment = f"Performs {method_name.replace('_', ' ').lower()} operation"
    
    # 添加参数说明
    params_text = ""
    if param_names:
        params_text = "\n * @param " + f"\n * @param ".join([f"{name} the {name} parameter" for name in param_names])
    
    # 添加返回值说明
    return_text = ""
    if return_type and return_type != "void":
        return_text = f"\n * @return the {return_type.lower()} result"
    
    return f"/**\n * {comment}.{params_text}{return_text}\n */"

def fix_file_comments(file_path, mode='remove'):
    """
    修复文件中的注释
    mode: 'remove' - 删除所有注释
          'replace' - 用英文替换有乱码的注释
    """
    try:
        with open(file_path, 'rb') as f:
            raw_data = f.read()
            
        # 检测编码
        detected = chardet.detect(raw_data)
        encoding = detected['encoding']
        
        # 尝试解码
        try:
            content = raw_data.decode(encoding or 'utf-8')
        except:
            content = raw_data.decode('utf-8', errors='replace')
        
        if mode == 'remove':
            # 删除所有注释
            # 单行注释
            content = re.sub(r'//.*$', '', content, flags=re.MULTILINE)
            # 多行注释
            content = re.sub(r'/\*.*?\*/', '', content, flags=re.DOTALL | re.MULTILINE)
        elif mode == 'replace':
            # 只替换有乱码的注释
            # 保留单行注释
            lines = content.split('\n')
            new_lines = []
            
            for line in lines:
                # 检查单行注释
                if '//' in line:
                    comment_start = line.find('//')
                    comment = line[comment_start:]
                    if is_garbled_chinese(comment):
                        # 删除注释部分
                        line = line[:comment_start].rstrip()
                
                new_lines.append(line)
            
            content = '\n'.join(new_lines)
            
            # 处理多行注释
            def replace_multiline_comment(match):
                comment = match.group(0)
                if is_garbled_chinese(comment):
                    # 尝试判断是类、方法还是字段注释
                    if "/**" in comment:
                        # Javadoc注释，尝试生成简单的英文注释
                        return "/**\n * Method comment.\n */"
                    else:
                        return ""
                return comment
            
            content = re.sub(r'/\*.*?\*/', replace_multiline_comment, content, flags=re.DOTALL | re.MULTILINE)
        
        # 确保文件以换行符结束
        if content and not content.endswith('\n'):
            content += '\n'
        
        # 以UTF-8编码写回文件
        with open(file_path, 'w', encoding='utf-8', newline='\n') as f:
            f.write(content)
            
        return True
    except Exception as e:
        print(f"处理文件 {file_path} 时出错: {e}")
        return False

def find_java_files(directory):
    """查找所有Java文件"""
    java_files = []
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.java'):
                java_files.append(os.path.join(root, file))
    return java_files

def main():
    """主函数"""
    print("Java文件注释修复工具")
    print("1. 删除所有注释")
    print("2. 只替换有乱码的注释")
    
    choice = input("请选择修复模式 (1/2): ").strip()
    
    if choice == '1':
        mode = 'remove'
        print("\n将删除所有Java文件的注释...")
    elif choice == '2':
        mode = 'replace'
        print("\n将替换有乱码的注释...")
    else:
        print("无效选择")
        return
    
    confirm = input("确定要继续吗? (y/n): ").strip().lower()
    if confirm != 'y':
        print("操作已取消")
        return
    
    java_last_war_dir = Path(__file__).parent.parent.parent
    java_files = find_java_files(java_last_war_dir)
    
    print(f"找到 {len(java_files)} 个Java文件")
    
    fixed_count = 0
    failed_count = 0
    
    for file_path in java_files:
        relative_path = os.path.relpath(file_path, java_last_war_dir)
        print(f"处理: {relative_path}")
        
        if fix_file_comments(file_path, mode):
            fixed_count += 1
        else:
            failed_count += 1
    
    print(f"\n处理完成:")
    print(f"成功修复: {fixed_count} 个文件")
    print(f"失败: {failed_count} 个文件")

if __name__ == "__main__":
    main()